package com.xtedu.examproject.controller;


import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;

@WebServlet(
        name = "ContextDemoServlet",
        urlPatterns = {"/contextDemo"},
        initParams = {
                @WebInitParam(name = "defaultLocale", value = "en_US")
        }
)
public class ContextDemoServlet extends HttpServlet {

    private Properties appConfig;
    private int visitorCount;

    @Override
    public void init() throws ServletException {
        ServletContext context = getServletContext();

        // 1. 加载全局配置
        String configFile = context.getInitParameter("configFile");
        if (configFile != null) {
            try (InputStream is = context.getResourceAsStream(configFile)) {
                appConfig = new Properties();
                appConfig.load(is);
                context.log("Successfully loaded application configuration");
            } catch (IOException e) {
                context.log("Failed to load application configuration", e);
                throw new ServletException("Configuration loading failed", e);
            }
        }

        // 2. 初始化访问计数器
        Object count = context.getAttribute("visitorCount");
        visitorCount = (count != null) ? (Integer) count : 0;

        // 3. 记录初始化完成
        String defaultLocale = getServletConfig().getInitParameter("defaultLocale");
        context.log("ContextDemoServlet initialized with default locale: " + defaultLocale);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        ServletContext context = getServletContext();

        // 1. 设置响应内容类型
        resp.setContentType("text/html;charset=UTF-8");

        // 2. 获取各种上下文信息
        String appName = context.getInitParameter("appName");
        String adminEmail = context.getInitParameter("adminEmail");
        String realPath = context.getRealPath("/images/logo.png");

        // 3. 更新访问计数器
        synchronized (this) {
            visitorCount++;
            context.setAttribute("visitorCount", visitorCount);
        }

        // 4. 记录访问日志
        String clientIP = req.getRemoteAddr();
        context.log("Request from IP: " + clientIP + " at " + new Date());

        // 5. 生成响应
        PrintWriter out = resp.getWriter();
        try {
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Context Demo</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Application Information</h1>");
            out.println("<ul>");
            out.println("<li>Application Name: " + escapeHtml(appName) + "</li>");
            out.println("<li>Admin Email: " + escapeHtml(adminEmail) + "</li>");
            out.println("<li>Visitor Count: " + visitorCount + "</li>");
            out.println("<li>Logo Path: " + escapeHtml(realPath) + "</li>");
            out.println("<li>Server Info: " + escapeHtml(context.getServerInfo()) + "</li>");

            // 显示配置属性
            if (appConfig != null && !appConfig.isEmpty()) {
                out.println("<h2>Application Configuration</h2>");
                out.println("<ul>");
                for (String key : appConfig.stringPropertyNames()) {
                    out.println("<li>" + escapeHtml(key) + ": " +
                            escapeHtml(appConfig.getProperty(key)) + "</li>");
                }
                out.println("</ul>");
            }

            out.println("</ul>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 重定向到GET处理
        doGet(req, resp);
    }

    @Override
    public void destroy() {
        // 清理资源
        appConfig = null;
        getServletContext().log("ContextDemoServlet destroyed");
    }

    // 辅助方法：防止XSS攻击
    private String escapeHtml(String input) {
        if (input == null) {
            return "";
        }
        return input.replace("&", "&amp;")
                .replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#39;");
    }
}